﻿using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Trentacular.SharePoint.StsAdmin.Util
{
    public static class SPUtil
    {
        public static SPSolution GetSolutionByName(this SPFarm farm, string solutionName)
        {
            return farm.Solutions
                .FirstOrDefault(s => s.Name.Equals(solutionName, StringComparison.InvariantCultureIgnoreCase));
        }

        public static string GetUrl(this SPWebApplication webApplication)
        {
            foreach (var alternateUrl in webApplication.AlternateUrls)
            {
                if (alternateUrl.UrlZone == SPUrlZone.Default)
                    return alternateUrl.IncomingUrl;
            }

            return webApplication.AlternateUrls[0].IncomingUrl;
        }

        public static SPWebApplication GetWebApplication(Guid webApplicationId)
        {
            var adminWebApp = SPAdministrationWebApplication.Local;
            if (adminWebApp != null && adminWebApp.Id.Equals(webApplicationId))
                return adminWebApp;

            var service = SPFarm.Local.Services.GetValue<SPWebService>("");
            return service.WebApplications[webApplicationId];
        }

        #region Feature Helpers

        public static bool IsActivated(this SPFeatureCollection features, Guid featureId)
        {
            return features.Cast<SPFeature>().FirstOrDefault(f => f.DefinitionId.Equals(featureId)) != null;
        }

        public static void EnsureActivated(this SPFeatureCollection features, Guid featureId)
        {
            if (!IsActivated(features, featureId))
                features.Add(featureId);
        }

        public static void EnsureDeactivated(this SPFeatureCollection features, Guid featureId)
        {
            if (IsActivated(features, featureId))
                features.Remove(featureId);
        }

        public static bool Exists(this SPFeatureDefinitionCollection featureDefinitions, Guid featureDefinitionId)
        {
            return featureDefinitions.FirstOrDefault(fd => fd.Id.Equals(featureDefinitionId)) != null;
        }

        #endregion
    }
}
